<template>
    <el-header height="60px" class="fixed-header">
        <div class="header-left">
            <h2>房屋租赁系统</h2>
        </div>



        <div class="flex flex-wrap gap-4 items-center">

        </div>
        <!-- 智能搜索框 -->
        <!-- 选择列表，按地区和户型搜索 -->
        <div class="search-container" v-if="userRole==2">
            <el-input v-model="input" style="width: 240px" placeholder="点击搜索" @click="handleInputClick" />
            <el-button type="primary" @click="showall">显示全部</el-button>
        </div>


        <div class="header-right">
            <!-- 已登录显示用户头像和下拉菜单 -->
            <template v-if="isLogin">
                <el-dropdown>
                    <span class="el-dropdown-link">
                        <el-avatar :size="32" :src="userAvatar"></el-avatar>
                        <el-icon class="el-icon--right"><arrow-down /></el-icon>
                    </span>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item @click="goToUserInfo">个人信息</el-dropdown-item>
                            <el-dropdown-item @click="updatePassword">修改密码</el-dropdown-item>
                            <el-dropdown-item @click="handleHistory" v-if="userRole == 1">反馈与建议</el-dropdown-item>
                            <el-dropdown-item @click="handleHistory"
                                v-if="userRole == 2 || userRole == 3">租赁历史</el-dropdown-item>
                            <el-dropdown-item @click="goToReport"
                                v-if="userRole == 2 || userRole == 3">房屋数据</el-dropdown-item>
                            <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
                            <el-dropdown-item @click="gochat" v-if="userRole == 3">租客留言</el-dropdown-item>
                            <el-dropdown-item @click="gochat" v-if="userRole == 2">联系客服</el-dropdown-item>
                            <el-dropdown-item @click="gochat" v-if="userRole == 1">消息管理</el-dropdown-item>

                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </template>
            <!-- 未登录显示登录和注册按钮 -->
            <template v-else>
                <el-button type="text" @click="goToLogin" class="login-btn">登录</el-button>
                <el-button type="text" @click="goToRegister" class="register-btn">注册</el-button>
            </template>
        </div>
    </el-header>
    <el-dialog v-model="updatePasswordDialogVisible" title="修改密码" width="30%" :close-on-click-modal="false">
        <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="100px">
            <el-form-item label="旧密码" prop="oldPassword">
                <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入旧密码"
                    show-password></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
                <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码"
                    show-password></el-input>
            </el-form-item>
            <el-form-item label="确认新密码" prop="confirmPassword">
                <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码"
                    show-password></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="updatePasswordDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleUpdatePassword">确认</el-button>
            </span>
        </template>
    </el-dialog>

    //点击输入框时,显示弹窗
    <el-dialog v-model="showSearchDialog" title="高级搜索" width="60%" :close-on-click-modal="true"
        @closed="resetSearchForm">
        <el-form :model="searchForm" label-width="80px">
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="关键词">
                        <el-input v-model="searchForm.keyword" placeholder="输入关键字" />
                    </el-form-item>
                    <el-form-item label="户型">
                        <el-select v-model="searchForm.houseType" placeholder="全部户型">
                            <el-option label="全部" value="" />
                            <el-option label="1室1厅" value="11" />
                            <el-option label="2室1厅" value="21" />
                            <el-option label="2室2厅" value="22" />
                            <el-option label="3室1厅" value="31" />
                            <el-option label="3室2厅" value="32" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="租赁方式">
                        <el-radio-group v-model="searchForm.rentType">
                            <el-radio-button label="整租" />
                            <el-radio-button label="合租" />
                            <el-radio-button label="全部" />
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="城市">
                        <el-select v-model="searchForm.region" placeholder="全部">
                            <el-option label="全部" value="" />
                            <el-option label="北京" value="北京" />
                            <el-option label="大连" value="大连" />
                            <el-option label="石家庄" value="石家庄" />
                            <el-option label="哈尔滨" value="哈尔滨" />
                            <el-option label="沈阳" value="沈阳" />
                            <el-option label="太原" value="太原" />
                            <el-option label="威海" value="威海" />
                            <el-option label="潍坊" value="潍坊" />
                            <el-option label="呼和浩特" value="呼和浩特" />
                            <el-option label="西安" value="西安" />
                            <el-option label="济南" value="济南" />
                            <el-option label="南京" value="南京" />
                            <el-option label="上海" value="上海" />
                            <el-option label="深圳" value="深圳" />
                            <el-option label="湖南" value="湖南" />


                        </el-select>
                    </el-form-item>
                    <el-form-item label="价格范围">
                        <div class="price-range">
                            <el-input-number v-model="searchForm.minPrice" :min="0" placeholder="最低价" />
                            <span class="separator">-</span>
                            <el-input-number v-model="searchForm.maxPrice" :min="0" placeholder="最高价" />
                        </div>
                    </el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                </el-col>
            </el-row>
        </el-form>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ArrowDown } from '@element-plus/icons-vue'
import apiClient from '@/api/api'
import { ElMessage } from "element-plus"
import store from '@/store'


// 修改密码对话框是否显示
const updatePasswordDialogVisible = ref(false)
// 修改密码表单数据
const passwordForm = ref({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
})
// 修改密码表单验证规则
const passwordRules = {
    oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
    newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度至少为6位', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
            validator: (rule: any, value: string, callback: (error?: Error) => void) => {
                if (value !== passwordForm.value.newPassword) {
                    callback(new Error('两次输入的密码不一致'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ]
}

const passwordFormRef = ref()

const updatePassword = () => {
    updatePasswordDialogVisible.value = true
}

const handleUpdatePassword = async () => {
    if (!passwordFormRef.value) return
    await passwordFormRef.value.validate(async (valid: boolean) => {
        if (valid) {
            try {
                const response = await apiClient.put('/user/updatePassword', {
                    oldPassword: passwordForm.value.oldPassword,
                    newPassword: passwordForm.value.newPassword
                })
                if (response.data.code === 1) {
                    ElMessage.success('密码修改成功, 请重新登录')

                    updatePasswordDialogVisible.value = false
                    // 重置表单
                    passwordForm.value.oldPassword = ''
                    passwordForm.value.newPassword = ''
                    passwordForm.value.confirmPassword = ''

                    router.push('/login')
                    localStorage.removeItem('token')
                } else {
                    ElMessage.error(response.data.message || '密码修改失败')
                }
            } catch (error) {
                ElMessage.error('密码修改失败')
            }
        }
    })
}

// 从store中获取用户登录状态和身份信息
const isLogin = ref(store.getters.checkUserLogin)
const userRole = ref(store.getters.getUserIdentity) // 1: 管理员, 2: 租客, 3: 房东

// 创建路由实例
const router = useRouter()

// 设置默认用户头像
const userAvatar = ref(store.getters.getUserAvatar||'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png')

// 跳转到用户信息页面
const goToUserInfo = () => {
    router.push('/user')
}

// 跳转到登录页面
const goToLogin = () => {
    router.push('/login')
}

// 跳转到注册页面
const goToRegister = () => {
    router.push('/register')
}
// 跳转到报表页面
const goToReport = () => {
    router.push('/report');
};

// 处理用户登出
const handleLogout = () => {
    localStorage.removeItem('token')
    localStorage.removeItem('userId')
    localStorage.removeItem('userRole')
    router.push('/login')
}
// 跳转到租赁历史页面
const handleHistory = () => {
    router.push('/history')
}
onMounted(async () => {
    // 获取用户名和头像
    /*await apiClient.get('/user/getUserAvatar')
        .then(response => {
            if (response.data.code === 1) {
                const { avatar, role } = response.data.data
                userAvatar.value = avatar || userAvatar.value
                isLogin.value = true
                userRole.value = role || userRole.value
            } else {
                isLogin.value = false
                userRole.value = 0
            }
        }).catch(error => {
            console.error('获取用户信息失败', error)
            isLogin.value = false
            userRole.value = 0
        })*/
})
//点击输入框

// 新增搜索相关代码
const showSearchDialog = ref(false)
const searchForm = ref({
    keyword: '',
    region: '',
    houseType: '',
    rentType: '',
    minPrice: null,
    maxPrice: null
})
const handleInputClick = () => {
    showSearchDialog.value = true
}
// 添加重置表单方法
const resetSearchForm = () => {
    searchForm.value = {
        keyword: '',
        region: '',
        houseType: '',
        rentType: '',
        minPrice: null,
        maxPrice: null
    }
}

// 搜索功能实现
const input = ref('')
const handleSearch = () => {
    // if (!input.value.trim()) {
    //     ElMessage.warning('请输入搜索内容')
    //     return
    // }
    //点击搜索将数据发送给后端
    const params = {
        page: 1,
        pageSize: 12,
        keyword: searchForm.value.keyword,
        region: searchForm.value.region,
        houseType: searchForm.value.houseType,
        rentType: searchForm.value.rentType === '全部' ? '' : searchForm.value.rentType || '',
        minPrice: searchForm.value.minPrice,
        maxPrice: searchForm.value.maxPrice
    }
    // 将筛选数据信息传给主页面，在主页面里面请求
    router.push({ path: '/', query: params })
    showSearchDialog.value = false
}
//点击显示全部
const showall = () => {
    // 将筛选数据信息传给主页面，在主页面里面请求
    router.push({ path: '/' })
    showSearchDialog.value = false
}
// 跳转聊天室
const gochat = () => {
    //router.push('/chat')
    //携带聊天目标id
    //如果是租客，默认目标是管理员
    if(userRole.value==2){
      router.push({ path: '/chat', query: { targetId: 1 } })
    }
    router.push('/chat')
    //如果是房东，默认目标是管理员
    if(userRole.value==3){
      router.push({ path: '/chat', query: { targetId: 1 } })
    }
}
</script>

<style scoped>
.fixed-header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1000;
    background-color: #409EFF;
    color: white;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-right {
    display: flex;
    align-items: center;
}

.el-dropdown-link {
    display: flex;
    align-items: center;
    color: white;
    cursor: pointer;
    outline: none;
}

.el-dropdown-link .el-avatar {
    transition: transform 0.3s ease;
    border: none;
    outline: none;
}

.el-dropdown-link:hover .el-avatar {
    transform: scale(1.1);
    border: none;
    outline: none;
}

.login-btn,
.register-btn {
    color: white;
    margin-left: 15px;
    font-size: 16px;
}

.login-btn:hover,
.register-btn:hover {
    color: #e6e6e6;
}
</style>